package booksys.books;

import booksys.common.Utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BooksService {

    public Map<String, Object> getBooksList(String bookID, BooksDto booksDto) {
        booksDto.setB_id(bookID);
        SqlSession sess = Utils.openSession();
        try {
            BooksDao dao = sess.getMapper(BooksDao.class);

            //执行映射器方法之前执行分页参数(页码，每页记录数)设置
            PageHelper.startPage(booksDto);


            List<Books> booksList = dao.findBooksList(booksDto);


            //执行映射器方法之后，立即执行PageInfo对象创建
            PageInfo<Books> pageInfo = new PageInfo<Books>(booksList);

            Map<String, Object> page = new HashMap<>();
            page.put("current", pageInfo.getPageNum());//当前页
            page.put("pageSize", pageInfo.getPageSize());//每页最大记录数
            page.put("total", pageInfo.getTotal());//总记录数
            page.put("pages", pageInfo.getPages());//总页数
            page.put("size", pageInfo.getSize());//当前页记录数
            page.put("list", pageInfo.getList());//当前页数据记录
            page.put("first", 1);
            page.put("pre", pageInfo.getPrePage());
            page.put("next", pageInfo.getNextPage());
            page.put("last", pageInfo.getPages());


            sess.commit();

            return page;

        } catch (Exception e) {
            sess.rollback();
            throw new RuntimeException("加载图书信息失败！", e);
        } finally {
            sess.close();
        }
    }
}
